package cn.tedu.tmall.admin.mall.service.impl;

import cn.tedu.tmall.admin.mall.dao.persist.repository.ICategoryRepository;
import cn.tedu.tmall.admin.mall.pojo.entity.Category;
import cn.tedu.tmall.admin.mall.pojo.parm.CategoryAddNewParm;
import cn.tedu.tmall.admin.mall.pojo.vo.CategoryStandardVO;
import cn.tedu.tmall.admin.mall.service.ICategoryService;
import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class CategoryServiceImpl implements ICategoryService {

    @Autowired
    ICategoryRepository categoryRepository;

    @Override
    public void addNew(CategoryAddNewParm categoryAddNewParm) {
        // 类名称唯一
        String name = categoryAddNewParm.getName();
        long count = categoryRepository.countByName(name);
        if (count > 0) {
            String message = "新增类别失败,尝试添加的类别已被占用";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }


        Long parentId = categoryAddNewParm.getParentId();
        CategoryStandardVO categoryStandardVO = null;
        //处理depth，并检查父级类别（如果指定了）是否存在
        Integer depth = 1;
        if (parentId == 0) {
        } else {
            categoryStandardVO = categoryRepository.getStandardById(parentId);
            if (categoryStandardVO == null) {
                String message = "新增类别失败，父级类别不存在！";
                throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
            }
            depth = categoryStandardVO.getDepth() + 1;
        }


        Category category = new Category();

        BeanUtils.copyProperties(categoryAddNewParm, category);
        category.setDepth(depth);
        category.setIsParent(0);
       int rows=categoryRepository.insert(category);
       if(rows!=1){
           String message="新增类别失败，服务器忙，请稍后重试!";
           throw new ServiceException(ServiceCode.ERROR_INSERT,message);
       }

        //处理父级类别的isParent

        if (parentId != 0 && categoryStandardVO.getIsParent() == 0) {
            //修改为父级类别
            Category categoryParent = new Category();
            categoryParent.setId(parentId);
            categoryParent.setIsParent(1);
            rows =categoryRepository.updateById(categoryParent);

            if(rows!=1){
                String message="修改类别失败，服务器忙，请稍后重试!";
                throw new ServiceException(ServiceCode.ERROR_UPDATE,message);
            }
        }
    }
}
